<template>
  <div id="life-channel-wrap">
    <!-- 选项卡区域 -->
    <div style="margin-bottom: 0.24rem">
      <!-- 一个配置项 -->
      <template v-if="lifeTabList.length === 1">
        <div class="one-tab">
          <img src="@/assets/icon_chongzhi.png" />{{
            lifeTabList[0].pageSignName
          }}
        </div>
      </template>
      <!-- 二个配置项 -->
      <template v-if="lifeTabList.length === 2">
        <two-tab
          :curTab="lifeCurTab"
          :tabList="lifeTabList"
          @selectLifeTab="handleChangeLifeTab"
        />
      </template>
      <!-- 三个配置项 -->
      <template v-else-if="lifeTabList.length === 3">
        <three-tab
          :curTab="lifeCurTab"
          :tabList="lifeTabList"
          @selectLifeTab="handleChangeLifeTab"
        />
      </template>
      <!-- 四个及以上配置项 -->
      <template v-else-if="lifeTabList.length >= 4">
        <multi-tab
          :curTab="lifeCurTab"
          :tabList="lifeTabList"
          @selectLifeTab="handleChangeLifeTab"
        />
      </template>
    </div>
    <!-- 输入框历史记录区域 -->
    <div class="history-record-wrap">
      <div class="life-input-wrap">
        <input
          ref="inputRef"
          class="life-input"
          v-model="curInputObj.value"
          :key="curInputObj.detailId"
          :type="curInputObj.inputType"
          :maxlength="curInputObj.maxlength"
          :placeholder="curInputObj.placeholder"
          :pattern="curInputObj.curPattern"
          @input="handleKeyUp"
          @click="onclick"
          @focus="handleFocus"
          @blur="handleBlur"
        />
        <div class="clear-wrap" @click.stop="handleClearInput">
          <i v-if="curInputObj.value" class="clear-icon">删除</i>
        </div>
      </div>
      <!-- 历史记录列表 -->
      <div
        class="history-list-wrap"
        v-if="isShowHistory && historyList.length > 0"
      >
        <ul class="history-list">
          <li
            v-for="(v, index) in historyList"
            :key="index"
            @click.stop="handleHistoryClick(v)"
          >
            {{ v | formatMobile }}
          </li>
        </ul>
        <div class="clear-history" @click.stop="handleClearHistory">
          清空历史记录
        </div>
      </div>
    </div>
    <!-- 充值金额列表 -->
    <ul class="recharge-list" v-if="conferenceSpCardCubeVos.length > 0">
      <li
        is="rechargeItem"
        v-for="(v, index) in splitList"
        :key="index"
        :prodObj="v"
        :paytype="curInputObj.showType"
        @click.native="handleItemClick(v, index)"
      ></li>
      <li
        class="recharge-item more"
        :class="{ agentItem: isAgent }"
        v-if="conferenceSpCardCubeVos.length > 6 && splitList.length === 5"
        @click.stop="handleExpand"
      >
        更多充值金额
      </li>
    </ul>
    <div class="tip" @click="lookTip" v-if="curInputObj.rechargeHintText">
      {{ curInputObj.rechargeHintText }}
      <img
        v-if="curInputObj.rechargeHint"
        src="../../../assets/system-help.png"
        alt=""
      />
    </div>
    <!-- 充值确认弹窗 -->
    <rechargePopup
      ref="rechargePopupRef"
      @onOk="handleRecharge"
      @onCancel="handlerCancel"
      :money="rechargeMoney"
      :account="rechargeAccount"
    />
    <tipPopup ref="tipPopup" :content="curInputObj.rechargeHint" @onOk="onOK" />
  </div>
</template>

<script>
import multiTab from './multiTab.vue';
import twoTab from './twoTab.vue';
import threeTab from './threeTab.vue';
import rechargeItem from './rechargeItem.vue';
import rechargePopup from './rechargePopup.vue';
import { goLink, getHostEnvironment } from '@/utils/util';
import tipPopup from './tipPopup.vue';
// 验证是否是手机号
const checkPhone = phone => {
  let bool = true;
  if (!/^1[3456789]\d{9}$/.test(phone)) {
    bool = false;
  }
  return bool;
};
// // 验证邮箱
const checkEmail = text => {
  const emailReg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
  let bool = true;
  if (!emailReg.test(text)) {
    bool = false;
  }
  return bool;
};
const checkNumber = num => {
  const numReg = /^[0-9]*$/;
  return numReg.test(num);
};

export default {
  name: 'lifeChannel',
  props: {
    lifeTabList: {
      type: Array,
      default: () => []
    },
    conferenceName: {
      type: String,
      default: ''
    },
    conferenceId: {
      type: [Number, String],
      default: 0
    }
  },
  components: {
    twoTab,
    threeTab,
    rechargeItem,
    rechargePopup,
    multiTab,
    tipPopup
  },
  data() {
    return {
      scrollHeight: 0,
      isExpand: false, // 是否展开
      isShowHistory: false, // 是否展示历史记录
      lifeCurTab: 0, // 当前选择的tab
      conferenceSpCardCubeVos: [], // 原始充值金额列表
      splitList: [], // 切割充值金额列表
      historyList: [], // 历史记录列表
      cache: {}, // tab选项卡数据缓存
      curInputObj: {
        detailId: -1,
        inputFormat: 0, // inputFormat: 1:数字输入框 2:自定义输入框 3:手机号输入框 4:邮箱输入框
        maxlength: 50,
        inputType: 'tel',
        placeholder: '',
        isError: true,
        value: '',
        selectIndex: -1,
        curPattern: '[0-9]*'
      }, // 选中选项卡下，输入框的基本信息
      rechargeMoney: '', // 充值金额
      rechargeAccount: '', // 充值账号
      currentProuctDetail: {}, // 当前选择的直充商品的对象
      oldLen: 0,
      reqId: '',
      tipShow: false
    };
  },
  computed: {
    curTab() {
      return this.lifeTabList[this.lifeCurTab];
    },
    // 是否是店长
    isAgent() {
      return true;
    }
  },
  filters: {
    formatMobile(phone) {
      let ret = '';
      if (phone) {
        ret = phone.replace(/^(.{3})(.*)(.{4})$/, '$1 $2 $3');
      }
      return ret;
    }
  },
  methods: {
    getHostEnvironment,
    handlerCancel() {},
    // 缓存
    addToCache(detailId, data) {
      this.cache[detailId] = data;
    },
    // 历史记录选择
    handleHistoryClick(item) {
      this.curInputObj.value = item;
      this.isShowHistory = false;
      this.curInputObj.isError = false;
    },
    // 清空历史记录
    handleClearHistory() {
      this.historyList = [];
      this.curInputObj.isError = false;
      const shopId = 11;
      localStorage.removeItem(`${shopId}List`);
    },
    // 键盘抬起
    handleKeyUp() {
      const { value, inputFormat } = this.curInputObj || {};
      let val = '';
      if (String(inputFormat) === '3') {
        this.isShowHistory = value.length < 1;
      }
      if (String(inputFormat) === '3') {
        // 手机号输入框
        val = value.replace(/\D/g, '').substring(0, 11);
        const nowIndex = this.getCursortPosition(this.$refs.inputRef);
        const valueLen = val.length;
        this.curInputObj.isError = true;
        if (valueLen === 11) {
          // this.$refs.inputRef.blur();
          const bool = checkPhone(val);
          this.curInputObj.isError = !bool;
          if (!bool) {
            this.$toast('手机号码输入有误，请重新输入');
          }
        }
        if (valueLen > 3 && valueLen < 8) {
          this.curInputObj.value = `${val.substr(0, 3)} ${val.substr(3)}`;
        } else if (valueLen >= 8) {
          this.curInputObj.value = `${val.substr(0, 3)} ${val.substr(
            3,
            4
          )} ${val.substr(7)}`;
        } else {
          this.curInputObj.value = val;
        }
        // 重新赋值之后设置光标的位置
        this.setCurIndex(nowIndex, this.curInputObj.value);
      } else if (String(inputFormat) === '1') {
        // 数字输入框
        val = value.replace(/\D/g, '').substring(0, 50);
        this.curInputObj.isError = !val;
      } else if (String(inputFormat) === '4') {
        // 邮箱格式
        // const bool = checkEmail(value);
        this.curInputObj.isError = !value;
        // if (!bool) {
        //   this.$toast('邮箱输入有误，请重新输入');
        // }
      } else if (String(inputFormat) === '2') {
        // 自定义
        val = value;
        this.curInputObj.isError = !val;
      } else {
        let bool = true;
        const validArr = inputFormat.split(',');
        for (let i = 0; i < validArr.length; i += 1) {
          if (
            (validArr[i] === '1' && checkNumber(value)) ||
            (validArr[i] === '2' && value !== '') ||
            (validArr[i] === '3' && checkPhone(value)) ||
            (validArr[i] === '4' && checkEmail(value))
          ) {
            bool = false;
            break;
          }
        }
        this.curInputObj.isError = bool;
      }
      // 过滤历史记录
      // this.historyList = this.historyList.filter(item => item.startsWith(val));
    },
    setCurIndex(nowIndex, value) {
      const len = value.length;
      setTimeout(() => {
        let pos = nowIndex;
        // 说明是新增操作
        if (len > this.oldLen) {
          if (nowIndex === 4 || nowIndex === 9) {
            pos += 1;
          }
        } else if (len > this.oldLen) {
          // 删除操作
          if (nowIndex === 4 || nowIndex === 9) {
            pos -= 1;
          }
        }
        this.$refs.inputRef.selectionStart = pos;
        this.$refs.inputRef.selectionEnd = pos;
        this.oldLen = this.curInputObj.value.length;
      }, 0);
    },
    onclick() {
      // const nowIndex = this.getCursortPosition(
      //   document.querySelector('.life-input')
      // );
      // if (nowIndex === 4 || nowIndex === 9) {
      //   this.setCaretPosition(
      //     document.querySelector('.life-input'),
      //     nowIndex - 1
      //   );
      // }
    },
    // 获得焦点
    handleFocus() {
      this.isShowHistory =
        this.historyList.length > 0 &&
        String(this.curInputObj.inputFormat) === '3' &&
        this.curInputObj.value.length === 0;
      // this.historyList = getOrderHistory(`${staticQuery.shopId}List`);
      this.scrollToTop('focus');
    },
    // 失去焦点
    handleBlur() {
      // if (String(this.curInputObj.inputFormat) === '4') {
      //   // 邮箱格式
      //   const bool = checkEmail(this.curInputObj.value);
      //   if (!bool) {
      //     this.$toast('邮箱输入有误，请重新输入');
      //   }
      // }
      // this.scrollToTop('blur');
    },
    scrollToTop(key) {
      const lifeChannelDOM = document.getElementById('life-channel-wrap');
      const { top } = lifeChannelDOM.getBoundingClientRect();
      const headerDOM = document.getElementById('header');

      // // 失焦下，生活频道区域不在顶部时处理
      if (key === 'blur' && top > 0) {
        return;
      }
      // alert(top)
      const headerHeight = headerDOM.offsetHeight;
      const lifeChannelHeight = lifeChannelDOM.offsetHeight;
      const scrollHeight = headerHeight - lifeChannelHeight;
      // this.scrollHeight = scrollHeight;
      window.scroll(0, scrollHeight);
    },
    // 清空输入框
    handleClearInput() {
      this.curInputObj.value = '';
      this.isShowHistory = false;
    },
    // tab选项卡选择
    handleChangeLifeTab(index) {
      if (this.lifeCurTab === index) {
        return;
      }

      this.lifeCurTab = index;
      this.isExpand = false;
      this.isShowHistory = false;
      // 切换tab时，先缓存当前输入框数据
      this.cache[this.curInputObj.detailId] = {
        ...this.cache[this.curInputObj.detailId],
        ...this.curInputObj
      };
      // 查看是否有缓存，并取值
      const { detailId } = this.lifeTabList[this.lifeCurTab] || {};
      if (this.cache[detailId]) {
        const { conferenceSpCardCubeVos, ...rest } = this.cache[detailId];
        this.curInputObj = rest;
        this.conferenceSpCardCubeVos = conferenceSpCardCubeVos || [];
        this.splitList =
          conferenceSpCardCubeVos.length > 6
            ? conferenceSpCardCubeVos.slice(0, 5)
            : conferenceSpCardCubeVos || [];
      } else {
        const { conferenceSpCardCubeVos, ...rest } = this.lifeTabList[index];
        this.curInputObj = rest;
        this.conferenceSpCardCubeVos = conferenceSpCardCubeVos || [];
        this.splitList =
          conferenceSpCardCubeVos.length > 6
            ? conferenceSpCardCubeVos.slice(0, 5)
            : conferenceSpCardCubeVos || [];
      }
      // this.historyList = getOrderHistory(`${staticQuery.shopId}List`);
      if (
        String(this.lifeTabList[index].inputFormat) === '3' &&
        this.historyList.length > 0
      ) {
        this.curInputObj.value =
          this.curInputObj.value.length === 0
            ? this.historyList[0]
            : this.curInputObj.value;
      }
    },
    // 更多金额点击
    handleExpand() {
      this.splitList = this.conferenceSpCardCubeVos;
    },
    // 充值金额选择
    handleItemClick(v) {
      this.prodObj = v;
      const { inputFormat, value, placeholder } = this.curInputObj || {};
      // 记录当前选中的充值项
      this.curInputObj.selectIndex = v.id;
      // 充值选项点击处理
      const { type, conferenceSpCardPrdInfo, conferenceSpCardCubeImageVo } = v;
      if (type === 0) {
        if (v.conferenceSpCardPrdInfo && v.conferenceSpCardPrdInfo.sellOut) {
          return;
        }
        if (!value) {
          this.$toast(placeholder);
        }
        if (
          String(inputFormat) === '3' &&
          !checkPhone(value.replace(/\D/g, '').substring(0, 11))
        ) {
          this.$toast(placeholder);
          return;
        }
        if (String(inputFormat) === '4' && !checkEmail(value)) {
          this.$toast(placeholder);
          return;
        }
        const Reg = /^[+]{0,1}(\d+)$/;
        if (String(inputFormat) === '1' && !Reg.test(value)) {
          this.$toast(placeholder);
          return;
        }
        this.currentProuctDetail = v;
        // 输入框显示且无值时，直接return
        if (inputFormat !== 0 && !value) return;
        if (
          this.lifeTabList[this.lifeCurTab].inputFormat === 3 &&
          checkPhone(value)
        )
          return;
        if (this.curInputObj.showType === 0) {
          this.rechargeMoney = `${conferenceSpCardPrdInfo.tagPrice}元`;
        } else {
          this.rechargeMoney = conferenceSpCardPrdInfo.skuBO.size;
        }
        this.rechargeAccount = value.replace(/\s+/g, '');
        this.$refs.rechargePopupRef.showDialog = true;
      } else if (type === 1 && conferenceSpCardCubeImageVo.imgHerfH5) {
        // 链接类型处理
        const { imgHerfH5 } = conferenceSpCardCubeImageVo || {};
        if (imgHerfH5) {
          goLink(imgHerfH5, (params, path) => {
            if (path === 'commonActivity') {
              this.$router
                .push({
                  path,
                  query: {
                    ...params,
                    shopId: this.$route.query.shopId
                  }
                })
                .catch(err => {
                  console.log(err);
                });
              return;
            }
            this.$router.push({
              path,
              query: {
                ...params,
                shopId: this.$route.query.shopId
              }
            });
          });
        }
      }
    },
    // 立即充值
    handleRecharge() {
      // 创建订单
      /*this.$refs.rechargePopupRef.isLoading = true;
      const shopId = '';
      const obj = {
        shopBizCode: shopId,
        distributorCode: this.$route.query.distributorId || '',
        products: [
          {
            id: this.currentProuctDetail.conferenceSpCardPrdInfo.productNo,
            skuId: this.currentProuctDetail.conferenceSpCardPrdInfo.skuBO.no,
            quantity: 1 // 数量
          }
        ],
        createSource: 1, // 下单来源 1商详页立即支付下单 2购物车下单
        sourceUrl: '', // getSourceUrl(),
        channel: this.$route.query.channel, // 订单渠道 h5Mall 、app2H5
        accountNumber: this.curInputObj.value.replace(/\s+/g, '') // 直充商品充值账号   需要区分手机号和账号
      };*/
      /*createOrder(obj)
        .then(res => {
          if (res.code === 200 && res.success) {
            if (
              String(this.curInputObj.inputFormat) === '3' &&
              this.historyList.indexOf(this.curInputObj.value) === -1
            ) {
              // setOrderHistory(
              //   `${staticQuery.shopId}List`,
              //   this.curInputObj.value
              // );
            }
            this.reqId = res.data;
            if (getHostEnvironment() === 'browser') {
              this.$router.replace({
                path: 'checkout',
                query: {
                  orderId: this.reqId
                }
              });
            } else if (getHostEnvironment() === 'wechat') {
              this.pay(res.data);
            }
          } else {
            this.$refs.rechargePopupRef.isLoading = false;
            this.$refs.rechargePopupRef.showDialog = false;
            this.$toast.fail(res.message);
          }
        })
        .catch(err => {
          this.$refs.rechargePopupRef.isLoading = false;
          this.$refs.rechargePopupRef.showDialog = false;
          this.$toast.fail(err.message || '创建订单失败');
        });*/
    },
    pay() {
      /*createPayment({ reqId: data }).then(res => {
        if (res.code === 200 && res.success && res.data) {
          this.onBridgeReady(JSON.parse(res.data));
        } else {
          this.$toast.fail(res.message);
        }
        this.$refs.rechargePopupRef.isLoading = false;
        this.$refs.rechargePopupRef.showDialog = false;
      });*/
    },
    onBridgeReady(obj) {
      // 唤起微信支付
      /* eslint-disable-next-line no-undef */
      WeixinJSBridge.invoke('getBrandWCPayRequest', obj, res => {
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          this.$toast('支付成功!');
          this.$router.replace({
            name: 'success',
            query: { orderId: this.reqId }
          });
        } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          this.$toast('支付取消!');
        } else {
          this.$toast.fail('支付失败');
        }
      });
    },
    getCursortPosition(element) {
      let CaretPos = 0;
      if (document.selection) {
        // 支持IE
        element.focus();
        const Sel = document.selection.createRange();
        Sel.moveStart('character', -element.value.length);
        CaretPos = Sel.text.length;
      } else if (element.selectionStart || element.selectionStart === '0')
        // 支持firefox
        CaretPos = element.selectionStart;
      return CaretPos;
    },
    lookTip() {
      this.$refs.tipPopup.isShow = true;
      this.$emit('open');
    },
    onOK() {
      this.$emit('close');
    }
  },
  mounted() {
    const list = this.lifeTabList || [];
    list.forEach((item, index) => {
      const {
        detailId,
        configId,
        cubeNum,
        inputFormat,
        rechargeHint,
        inputHintText,
        conferenceSpCardCubeVos,
        rechargeHintText,
        showType
      } = item;
      // inputFormat:  1:数字输入框 2:自定义输入框 3:手机号输入框 4:邮箱输入框
      let inputType = '';
      let maxlength = 50;
      let curPattern = '';
      switch (String(inputFormat)) {
        case '1':
          inputType = 'tel';
          curPattern = '/[0-9]*/';
          break;
        case '2':
          inputType = 'text';
          break;
        case '3':
          inputType = 'tel';
          maxlength = 13;
          curPattern = '/[0-9]*/';
          break;
        case '4':
          inputType = 'text';
          break;
        default:
          break;
      }
      const data = {
        detailId,
        configId,
        cubeNum,
        inputFormat,
        maxlength,
        inputType,
        rechargeHint,
        placeholder: inputHintText,
        isError: true,
        value: '',
        selectIndex: -1,
        conferenceSpCardCubeVos,
        curPattern,
        showType,
        rechargeHintText
      };
      if (index === 0) {
        this.curInputObj = data;
        this.conferenceSpCardCubeVos = conferenceSpCardCubeVos || [];
        this.splitList =
          conferenceSpCardCubeVos.length > 6
            ? conferenceSpCardCubeVos.slice(0, 5)
            : conferenceSpCardCubeVos || [];
      }
      this.addToCache(detailId, data);
    });
    this.curInputObj.isError = false;
  }
};
</script>

<style lang="scss" scoped>
#life-channel-wrap {
  width: 100%;
  background: #fff;
  // background: #bd4444;
  border-radius: 6px;
  // overflow: hidden;
  padding-bottom: 10px;

  .one-tab {
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: #333;
    // line-height: 20px;
    padding-left: 12px;
    padding-top: 12px;
    // height: 40px;
    display: flex;
    align-items: center;
    img {
      width: 22px;
      height: 22px;
      margin-right: 2px;
    }
  }

  .history-record-wrap {
    position: relative;
  }

  .history-list-wrap {
    position: absolute;
    left: 0;
    top: 40px;
    width: 100%;
    background-color: #fff;
    padding: 0 10px;
    z-index: 1004;
    border-radius: 0 0 2px 2px;
    box-sizing: border-box;
  }

  .history-list {
    padding-top: 12px;
    li {
      font-size: 16px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: #333;
      line-height: 49px;
      border-bottom: 1px solid #f0f0f0;
    }
  }

  .clear-history {
    font-size: 12px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: #333;
    line-height: 17px;
    padding: 10px 0 11px;
    text-align: center;
    line-height: 17px;
  }
}

.life-input-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
  position: relative;

  .life-input {
    width: 306px;
    height: 30px;
    font-size: 22px;
    padding-left: 10px;
    line-height: 28px;
    color: #333;
    font-family: PingFangSC-Regular;
    background-color: transparent;
    -webkit-appearance: none;
    outline: none;
    caret-color: #3976e9 !important;

    &::-webkit-input-placeholder {
      color: #ccc;
    }
  }

  .clear-wrap {
    position: absolute;
    right: 0;
    padding: 0 10px;
    height: 37px;
    display: flex;
    align-items: center;
  }

  .clear-icon {
    width: 18px;
    height: 18px;
    display: block;
    font-weight: normal;
    /*background: url('./../../../static/icon_delete2.png') no-repeat;
    background-size: 100% 100%;*/
  }
}

.recharge-list {
  padding: 0 3px;
  display: flex;
  flex-wrap: wrap;

  .recharge-item {
    width: 104px;
    border: 1px solid #f5a7a7;
    border-radius: 2px;
    margin: 0 6px 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    &.unable {
      border: 1px solid #ccc;
    }

    &.more {
      font-size: 14px;
      font-family: PingFangSC-Regular;
      color: rgba(51, 51, 51, 1);
      line-height: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.tip {
  height: 14px;
  font-size: 11px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #f28e8e;
  line-height: 14px;
  align-items: center;
  text-align: center;
  display: flex;
  justify-content: center;
  img {
    width: 10px;
    height: 10px;
    margin-left: 2px;
  }
}
.agentItem {
  height: 69px;
}
</style>
